<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="仓库名称" min-width="125">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
              :disabled="isDirectInOut && formData.length > 0"
              :filter-method="handleWareHouseFilterMethod"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
              :filter-method="handleFilterMethod"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="条码" min-width="150">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productBarCode" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="规格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productStandard`" class="mb-0px!">
            {{ row.productStandard }}
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="规格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productStandard`" class="mb-0px!">
            {{row.productStandard}}
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="1"
              :precision="0"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单价" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!">
            <el-input disabled v-model="row.totalPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加入库产品</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/pplanWarehouse'
import { StockApi } from '@/api/erp/stock/pplanStock'
import { erpCountFormatter, erpPriceInputFormatter, erpPriceMultiply, getSumValue } from '@/utils'
import type { SummaryMethodProps } from 'element-plus' // 导入表格合计所需类型

// 定义Props（保持原有逻辑）
const props = defineProps<{
  items: any[]
  disabled: boolean
  isDirectInOut: boolean
}>()

// 表单基础状态与数据
const formLoading = ref(false)
const formData = ref<any[]>([])
const formRef = ref<any>(null) // 修正表单Ref为单个Ref
const formRules = reactive({
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})

// -------------------------- 核心修改：产品列表回显问题修复 --------------------------
const productList = ref<ProductVO[]>([]) // 下拉显示用产品列表
const productAllList = ref<ProductVO[]>([]) // 完整产品列表（缓存所有数据）

// 加载完整产品列表（仅加载一次）
const loadAllProducts = async () => {
  if (productAllList.value.length > 0) return productAllList.value
  const data = await ProductApi.getProductSimpleList()
  productAllList.value = data
  return data
}

// 确保已选产品在下拉列表中
const ensureSelectedProductsInList = async () => {
  await loadAllProducts()
  const selectedProductIds = formData.value.map((item) => item.productId).filter(Boolean)
  selectedProductIds.forEach((id) => {
    const isExist = productList.value.some((item) => item.id === id)
    if (!isExist) {
      const product = productAllList.value.find((item) => item.id === id)
      if (product) productList.value.push(product)
    }
  })
}

// 修改产品过滤方法：包含已选产品
const handleFilterMethod = async (query?: string) => {
  await loadAllProducts()

  // 提取已选产品
  const selectedProducts = formData.value
    .map((item) => productAllList.value.find((p) => p.id === item.productId))
    .filter(Boolean)

  // 过滤数据
  let filtered = [] as ProductVO[]
  if (!query) {
    filtered = [...productAllList.value].slice(0, 200) // 保持首屏200条性能优化
  } else {
    filtered = productAllList.value.filter((p) =>
      p.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并去重
  productList.value = Array.from(
    new Map([...filtered, ...selectedProducts].map((p) => [p.id, p])).values()
  )
  return productList.value
}
// -----------------------------------------------------------------------------------

// -------------------------- 核心修改：仓库列表回显问题修复 --------------------------
const warehouseList = ref<WarehouseVO[]>([]) // 下拉显示用仓库列表
const warehouseAllList = ref<WarehouseVO[]>([]) // 完整仓库列表（缓存所有数据）
const defaultWarehouse = ref<WarehouseVO>(undefined)
const directWarehouse = ref<WarehouseVO>(undefined)

// 加载完整仓库列表（仅加载一次）
const loadAllWarehouses = async () => {
  if (warehouseAllList.value.length > 0) return warehouseAllList.value
  const data = await WarehouseApi.getWarehouseSimpleList()
  warehouseAllList.value = data
  // 初始化直入直出库和默认仓库（原有逻辑保留）
  directWarehouse.value = warehouseAllList.value.find((item) => item.name === '直入直出库')
  defaultWarehouse.value = warehouseAllList.value.find((item) => item.defaultStatus)
  return data
}

// 确保已选仓库在下拉列表中
const ensureSelectedWarehousesInList = async () => {
  await loadAllWarehouses()
  const selectedWarehouseIds = formData.value.map((item) => item.warehouseId).filter(Boolean)
  selectedWarehouseIds.forEach((id) => {
    const isExist = warehouseList.value.some((item) => item.id === id)
    if (!isExist) {
      const warehouse = warehouseAllList.value.find((item) => item.id === id)
      if (warehouse) warehouseList.value.push(warehouse)
    }
  })
}

// 修改仓库过滤方法：包含已选仓库
const handleWareHouseFilterMethod = async (query?: string) => {
  await loadAllWarehouses()

  // 提取已选仓库
  const selectedWarehouses = formData.value
    .map((item) => warehouseAllList.value.find((w) => w.id === item.warehouseId))
    .filter(Boolean)

  // 过滤数据
  let filtered = [] as WarehouseVO[]
  if (!query) {
    filtered = [...warehouseAllList.value].slice(0, 200) // 保持首屏200条性能优化
  } else {
    filtered = warehouseAllList.value.filter((w) =>
      w.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并去重
  warehouseList.value = Array.from(
    new Map([...selectedWarehouses, ...filtered].map((w) => [w.id, w])).values()
  )
  return warehouseList.value
}
// -----------------------------------------------------------------------------------

// 直入直出库自动设置逻辑（原有逻辑保留，仅修正数据来源）
const checkAndSetDirectWarehouse = () => {
  if (props.isDirectInOut && directWarehouse.value) {
    formData.value.forEach((row) => {
      row.warehouseId = directWarehouse.value!.id
    })
    // 确保直入直出库在下拉列表中
    ensureSelectedWarehousesInList()
  }
}

// 监听items变化（添加回显补全逻辑）
watch(
  () => props.items,
  async (val) => {
    formData.value = val || []
    checkAndSetDirectWarehouse()
    // 补全已选产品和仓库到下拉列表
    await ensureSelectedProductsInList()
    await ensureSelectedWarehousesInList()
  },
  { immediate: true, deep: true }
)

// 监听直入直出状态变化（原有逻辑保留）
watch(
  () => props.isDirectInOut,
  (newVal) => {
    checkAndSetDirectWarehouse()
  },
  { immediate: true }
)

// 监听产品数据变化计算总价（原有逻辑保留）
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    val.forEach((item) => {
      item.totalPrice = erpPriceMultiply(item.productPrice, item.count)
    })
  },
  { deep: true }
)

// 表格合计逻辑（原有逻辑保留，修正类型）
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalPrice'].includes(column.property as string)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 新增产品行（原有逻辑保留，修正仓库数据来源）
const handleAdd = () => {
  const row = {
    id: undefined,
    warehouseId:
      props.isDirectInOut && directWarehouse.value
        ? directWarehouse.value.id
        : defaultWarehouse.value?.id,
    productId: undefined,
    productUnitName: undefined,
    productStandard: undefined,
    productBarCode: undefined,
    productPrice: undefined,
    stockCount: undefined,
    count: 1,
    totalPrice: undefined,
    remark: undefined
  }
  formData.value.push(row)
  // 确保新增行的仓库在下拉列表中
  if (row.warehouseId) ensureSelectedWarehousesInList()
}

// 删除产品行（原有逻辑保留）
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

// 仓库变更处理（修正库存加载逻辑，确保数据来源正确）
const onChangeWarehouse = (warehouseId: any, row: any) => {
  // 从完整列表确认仓库存在（避免显示列表限制）
  const warehouse = warehouseAllList.value.find((item) => item.id === warehouseId)
  if (warehouse) setStockCount(row)
}

// 产品变更处理（修正产品信息来源为完整列表）
const onChangeProduct = (productId: any, row: any) => {
  // 从完整列表获取产品信息，避免显示列表限制
  const product = productAllList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.unitName
    ;(row.productStandard = product.productStandard), (row.productBarCode = product.barCode)
    row.productPrice = product.productPrice
  }
  setStockCount(row)
}

// 加载库存（原有逻辑保留）
const setStockCount = async (row: any) => {
  if (!row.productId || !row.warehouseId) {
    return
  }
  const stock = await StockApi.getStock2(row.productId, row.warehouseId)
  row.stockCount = stock ? stock.count : 0
}

// 表单验证（原有逻辑保留）
const validate = () => {
  return formRef.value?.validate()
}
defineExpose({ validate })

// 初始化（修改为加载完整列表后再初始化显示）
onMounted(async () => {
  // 先加载完整产品和仓库列表
  await loadAllProducts()
  await loadAllWarehouses()
  // 初始化显示列表（保持首屏200条）
  await handleFilterMethod()
  await handleWareHouseFilterMethod()

  // 默认添加一行（原有逻辑保留）
  if (formData.value.length === 0) {
    handleAdd()
  } else {
    // 补全已选数据到下拉列表
    await ensureSelectedProductsInList()
    await ensureSelectedWarehousesInList()
  }
})
</script>
